package com.sunny.region.action;

import com.opensymphony.xwork2.ActionContext;
import com.sunny.util.struts2.BaseAction;
import com.sunny.region.model.Regions;
import com.sunny.region.service.RegionsService;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by tongchengke on 2016/8/9.
 */

@Controller
@Scope("prototype")
public class RegionsAction extends BaseAction<Regions>{

    @Resource
    private RegionsService regionsService;

    public String toRegionView(){

        ActionContext actionContext = ActionContext.getContext();
        Map<String, Object> session = actionContext.getSession();


        session.put("user", "中国");

        return "success";
    }

    public void getRegionsById() throws IOException {

        regions = regionsService.selectByPrimaryKey(420000000000L);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(regions);

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
        response.getWriter().flush();
        response.getWriter().close();
    }

    public void getRegionsByPid() throws IOException {
        Long pid = regions.getPid();
        if(pid!=null){
            List<Regions> list = regionsService.selectRegionsByPid(pid);
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(list);

            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(json);
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    public void getRegionsByPage(){

    }

    private Regions regions;

    public Regions getRegions() {
        return regions;
    }

    public void setRegions(Regions regions) {
        this.regions = regions;
    }

    @Override
    public Regions getModel() {
        if(regions==null){
            regions = new Regions();
        }
        return regions;
    }
}
